package com.zmc.order.infrastructure.updater.order;

import com.zmc.common.constant.QueueConstant;
import com.zmc.common.domain.vo.good.GoodsUpVo;
import com.zmc.common.exception.base.BusinessException;
import com.zmc.order.feign.ProductFeignService;
import com.zmc.order.infrastructure.entity.OrderEntity;
import com.zmc.order.infrastructure.entity.OrderItemEntity;
import com.zmc.order.infrastructure.enums.OrderEnum;
import com.zmc.order.infrastructure.service.MerchantOrderService;
import com.zmc.order.infrastructure.service.OrderItemService;
import com.zmc.order.infrastructure.service.OrderService;
import org.apache.shardingsphere.transaction.annotation.ShardingSphereTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author：zmc
 * @Date：2025/5/15 17:42
 * 取消订单
 */

@Component
public class OrderCancelUpdater<T> implements OderUpdater<T> {

    public static Logger log = LoggerFactory.getLogger(OrderCancelUpdater.class);

    @Autowired
    private OrderService orderService;

    @Autowired
    private MerchantOrderService merchantOrderService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    @Transactional
    @ShardingSphereTransactionType(TransactionType.BASE)
    public void execute(T param) {
        String orderSn = (String) param;
        OrderEntity order = orderService.getByOrderSn(orderSn);
        if (order == null) {
            log.error("cancelOrder：查询订单不存在,orderSn:{}", orderSn);
            throw new BusinessException("取消订单异常，订单不存在");
        }
        if (OrderEnum.ORDER_STATUS_WAIT_FOR_PAY.getCode() != order.getStatus()) {
            log.error("cancelOrder：当前订单状态无法取消,orderId:{}, 订单状态：{}", orderSn, order.getStatus());
            throw new BusinessException("取消订单异常，状态异常");
        }
        List<OrderItemEntity> orderItemList = orderItemService.listByOrderSn(orderSn);
        if (CollectionUtils.isEmpty(orderItemList)) {
            log.error("cancelOrder：查询订单条目不存在,orderId:{}", orderSn);
            throw new BusinessException("取消订单异常，查询订单条目不存在");
        }
        //更新用户订单
        orderService.updateStatus(orderSn, OrderEnum.ORDER_STATUS_INVALID_ORDER.getCode());
        //更新商户订单
        merchantOrderService.updateStatus(order.getMerchantOrderSn(), OrderEnum.ORDER_STATUS_INVALID_ORDER.getCode());
        //解锁库存
        List<GoodsUpVo> collect = orderItemList.stream().map(item -> {
            GoodsUpVo vo = new GoodsUpVo();
            vo.setSkuId(item.getSkuId());
            vo.setCount(item.getSkuQuantity());
            return vo;
        }).collect(Collectors.toList());
        productFeignService.unlockStock(collect).valid();
        //返优惠卷
        List<OrderItemEntity> couponIdList = orderItemList.stream().filter(item -> item.getCouponId() != null).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(couponIdList)) {
            rabbitTemplate.convertAndSend(QueueConstant.COUPON_RETURN_EXCHANGE, QueueConstant.COUPON_RETURN_ROUTING_KEY, orderSn);
        }
    }
}
